package com.shuhe.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class HttpClient {

    private static Logger logger = Logger.getLogger(HttpClient.class);
    private static CloseableHttpClient httpClient = HttpClients.createDefault();

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
                    new TrustStrategy() {
                        @Override
                        public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                            return true;
                        }
                    }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String postHttp(String url, String bodyStr,
                                  Map<String, String> heads) throws Exception {
        try {
            HttpPost httpPost = new HttpPost(url);
            //设置超时时间
            int timeout = 60000 * 5;
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(timeout).setConnectionRequestTimeout(timeout)
                    .setSocketTimeout(timeout).build();
            httpPost.setConfig(requestConfig);
            //设置数据为utf-8编码
            //logger.info(bodyStr);
            JSONObject jsonObject = JSONObject.parseObject(bodyStr);
            StringEntity stringEntity = new StringEntity(jsonObject.toJSONString(), "utf-8");
            //设置请求编码
            stringEntity.setContentEncoding("utf-8");
            //设置请求类型
            httpPost.setHeader("Content-type", "application/json");
            for (String key : heads.keySet()) {
                String value = heads.get(key);
                httpPost.setHeader(key, value);
            }
            httpPost.setEntity(stringEntity);
            httpPost.setURI(new URI(url));
            HttpResponse result = httpClient.execute(httpPost);
            String responseJsonStr = EntityUtils.toString(result.getEntity(), "utf-8").trim();
            return responseJsonStr;
        } catch (Exception ex) {
            logger.info(ex);
            throw new Exception("访问服务超时");
        }
    }


    public static String getHttp(String url) throws Exception {
        try {
            // 创建Get请求
            HttpGet httpGet = new HttpGet(url);
            // 由客户端执行(发送)Get请求
            HttpResponse result = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            String responseJsonStr = EntityUtils.toString(result.getEntity(), "utf-8").trim();
            return responseJsonStr;
        } catch (Exception e) {
            throw new Exception("访问服务超时");
        }
    }

    public static String getHttp3(String url, HashMap<String, String> parms) throws Exception {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            URIBuilder uriBuilder = new URIBuilder(url);

            for (Map.Entry<String, String> entry : parms.entrySet()) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }

            URI uri = uriBuilder.build();
            // 创建Get请求
            HttpGet httpGet = new HttpGet(uri);
            // 由客户端执行(发送)Get请求
            HttpResponse result = httpClient.execute(httpGet);
            // 从响应模型中获取响应实体
            String responseJsonStr = EntityUtils.toString(result.getEntity(), "utf-8").trim();
            return responseJsonStr;
        } catch (Exception e) {
            throw new Exception("访问服务超时");
        }
    }

    public static Map<String, String> getAllHeaders(HttpServletRequest request) {
        // 获取所有头部名称
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> heads = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            if ("Cookie".equals(headerName) || "Host".equals(headerName) || "Postman-Token".equals(headerName)
                    || "Content-Length".equals(headerName)) {
                continue;
            }
            String headerValue = request.getHeader(headerName);
            heads.put(headerName, headerValue);
        }
        return heads;
    }
}
